import React, { Component } from 'react';
type Istate = {
  hasError: boolean;
};

class ErrorBoundary extends React.Component<any, Istate> {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }
  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    console.log('有错误');
    return { hasError: true };
  }
  componentDidCatch(error, info) {
    // You can also log the error to an error reporting service
  }
  render() {
    if (this.state.hasError) {
      console.log('有错误1');
      // You can render any custom fallback UI
      return <div>发生了错误</div>;
    }
    return this.props.children;
  }
}

class Comment extends Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  render() {
    if (this.state.count === 5) {
      // Simulate a JS error
      throw new Error('I crashed!');
    }
    return (
      <div>
        count:{this.state.count}
        <button onClick={this.setState({ count: this.state.count++ })}>
          增加
        </button>
      </div>
    );
  }
}

class Errc extends Component {
  render() {
    return (
      <div>
        <ErrorBoundary>
          <Comment></Comment>
        </ErrorBoundary>
      </div>
    );
  }
}

export default Errc;
